//职员管理

import React, {Component} from 'react';
import app from '../app';
import {Form, Input, Button, Table, Modal, Row, Upload, Icon, DatePicker, Select, Pagination} from 'antd';
import {activity} from '../value';
import '../css/other.css';
import moment from 'moment';
import {config} from "../config";

import {Editor} from 'react-draft-wysiwyg';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class ActivityList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchData: {},
            pagination: {current: 1, pageSize: 10, total: 0},
            data: [],
            currentPageSize: 0,
            pageCount: 0,
            imgUrl: '',
        }
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'order_number'
        },
        {
            title: '活动名称',
            dataIndex: 'activity_name'
        },
        {
            title: '活动说明',
            dataIndex: 'activity_explain'
        },
        {
            title: '活动类型',
            dataIndex: 'activity_type',
            render: activity_type => {
                let text = '';
                if (activity_type === '1') {
                    text = '满减';
                } else {
                    text = '折扣';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '开始时间',
            dataIndex: 'activity_startTime',
            render: activity_startTime => {
                return (
                    <span>{moment(activity_startTime).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '结束时间',
            dataIndex: 'activity_endTime',
            render: activity_endTime => {
                return (
                    <span>{moment(activity_endTime).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '创建时间',
            dataIndex: 'activity_createTime',
            render: activity_createTime => {
                return (
                    <span>{moment(activity_createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                )
            }
        },
        {
            title: '商品数',
            dataIndex: 'goodsCount'
        },
        {
            title: '状态',
            dataIndex: 'activity_status',
            render: activity_status => {
                let text = '';
                if (activity_status === '1') {
                    text = '未开始';
                } else if (activity_status === '2') {
                    text = '进行中';
                } else if (activity_status === '3') {
                    text = '已结束';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <div>
                        <Button type={'primary'} onClick={()=>this.handleRedirectToActivityEdit(data.activity_id)}>编辑</Button>
                        <Button style={{marginLeft: '10px'}} type="danger"
                                onClick={() => this.handleDeleteActivity(data.activity_id)}>删除</Button>
                    </div>
                )
            }
        },
    ];

    render() {
        // const rowSelection = {
        //     // 表格中复选框发生变化时
        //     onChange: (selectedRowKeys, selectedRows) => {
        //         let positionId = [];
        //         let positionName = [];
        //         positionId = selectedRowKeys;
        //         selectedRows.forEach((item) => {
        //             positionName.push(item.role_name);
        //         });
        //         this.setState({
        //             positionId: positionId,  //批量选中的职位ID
        //             positionName: positionName,
        //             selectCount: selectedRowKeys.length, //一共选择的职位数量
        //         })
        //     },
        //
        // };
        const {pagination, currentPageSize} = this.state;
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    满减活动列表
                </div>
                <SearchLists refresh={() => this.handleRefreshAfterCreate()}
                             clickSearch={(values) => this.handleGetValue(values)}
                             handleRedirectToActivityAdd={()=>this.handleRedirectToActivityAdd()}/>
                <div style={{fontSize: 12, marginBottom: 20, marginTop: 20}}>
                    当前第<span style={{color: 'red'}}>{pagination.current}</span>页, 当前页共<span
                    style={{color: 'red'}}>{currentPageSize}</span>条数据，一共<span
                    style={{color: 'red'}}>{pagination.total}</span>条数据
                </div>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={(record, index) => index}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={false}
                        onChange={this.handleTableChange}
                    />
                </Row>
                <Row style={{textAlign: 'right', marginTop: 20}}>
                    <Pagination {...pagination} showSizeChanger showQuickJumper
                                onChange={(page, pageSize) => this.handlePageOnChange(page, pageSize)}
                                onShowSizeChange={(current, size) => this.handleOnShowSizeChange(current, size)}/>
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        const param = {page: 1, size: 10};
        this.searchActivityList(param);
    }

    /**
     * 获取搜索条件
     */
    handleGetValue(data) {
        console.log(data);
        let startTime = '';
        let endTime = '';
        if (data.date && data.date.length > 0) {
            startTime = moment(data.date[0]._d).format('YYYY-MM-DD HH:mm:ss');
            endTime = moment(data.date[1]._d).format('YYYY-MM-DD HH:mm:ss');
        }
        const searchData = {
            startTime,
            endTime,
            nameSearch: data.activity_name,
            statusSearch: data.status
        };
        this.setState({searchData});
        const param = {
            page: 1,
            size: 10,
            ...searchData
        };
        this.searchActivityList(param);
    }

    /**
     * 处理创建后刷新事件
     */
    handleRefreshAfterCreate() {
        const param = {};
        this.searchProject(param);
    }

    /**
     * 处理删除后刷新事件
     */
    handleRefreshAfterDelete() {
        const {searchData} = this.state;
        const param = {
            ...searchData,
            page:1,
            size:10
        };
        this.searchActivityList(param);
    }

    /**
     * 处理更新后刷新事件
     */
    handleRefreshAfterUpdate() {
        const {searchData} = this.state;
        const param = {
            ...searchData
        };
        this.searchActivityList(param);
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 处理页码变化事件
     * @param page
     * @param pageSize
     */
    handlePageOnChange(page, pageSize) {
        console.log(page, pageSize);
        const {searchData} = this.state;
        const param = {
            page,
            size: pageSize,
            ...searchData
        };
        this.searchActivityList(param);
    }

    /**
     * 处理数量变化事件
     * @param current
     * @param size
     */
    handleOnShowSizeChange(current, size) {
        console.log(current, size);
        const {searchData} = this.state;
        const param = {
            page: current,
            size,
            ...searchData
        };
        this.searchActivityList(param);
    }

    /**
     * 查找活动列表
     * @param param
     */
    searchActivityList(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(activity.SEARCH_ACTIVITY_LIST, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                for (let i = 0; i < data.length; i++) {
                    data[i].order_number = i + 1;
                }
                const pagination = {total: result.count, current: param.page, pageSize: param.size};
                this.setState({pagination, data: data, loading: false, currentPageSize: data.length});
            } else {
                app.alert(result.msg, 'success', 2);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false, currentPageSize: 0});
            }
        });
    }

    /**
     * 删除活动
     * @param id
     */
    handleDeleteActivity(id) {
        let _this = this;
        confirm({
            content: '您确定要删除该活动吗？',
            onOk() {
                app.post(activity.UPDATE_ACTIVITY_ISABLE, {activity_id: id,activity_isable:'2'}).then((res) => {
                    if (res.code === 1) {
                        app.alert("删除成功", 'success', 1);
                        _this.handleRefreshAfterDelete();
                    } else {
                        app.alert(res.msg, 'error', 1);
                    }
                })
            },
            onCancel() {
            },
        });
    }

    /**
     * 跳转到新增满减活动页面
     */
    handleRedirectToActivityAdd() {
        this.props.history.push(config.path + '/home/activityAdd/:id');
    }

    /**
     * 跳转到编辑活动页面
     */
    handleRedirectToActivityEdit(id){
        this.props.history.push(config.path + '/home/activityAdd/'+id);
    }
}


class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            project_name: ''
        }
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY-MM-DD';
        return (
            <div style={{display: 'flex', marginTop: 10, marginBottom: 5}}>
                <div style={{display: 'flex', width: '220px', height: '28px'}}>
                    <div style={{width: 70, height: 28, lineHeight: '28px', color: '#000000'}}>活动名称：</div>
                    <Input onPressEnter={() => this.handleSearchComplain1()} onChange={(e) => this.handleOnChange(e)}
                           type="text" placeholder="活动名称" style={{width: 150}}/>
                </div>
                <div style={{display: 'flex', width: '320px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 100, height: 28, lineHeight: '28px', color: '#000000'}}>活动开始时间：</div>
                    <RangePicker format={dateFormat} style={{width: 220}} onChange={(e) => this.handleDateOnChange(e)}/>
                </div>
                <div style={{display: 'flex', width: '150px', height: '28px', marginLeft: 10}}>
                    <div style={{width: 50, height: 28, lineHeight: '28px', color: '#000000'}}>状态：</div>
                    <Select style={{width: 100}} placeholder={'请选择状态'} onChange={(e) => this.handleStatusOnchange(e)}>
                        <Option value="">全部</Option>
                        <Option value="1">未开始</Option>
                        <Option value="2">进行中</Option>
                        <Option value="3">已结束</Option>
                    </Select>
                </div>
                <div style={{display: 'flex', width: '120px', height: '28px', marginLeft: 20}}>
                    <Button type="primary" onClick={() => this.handleSearchComplain1()}>搜索</Button>
                    <Button type={'primary'} style={{marginLeft: 20}}
                            onClick={() => this.handleRedirectToActivityAdd()}>新建活动</Button>
                    {/*<AddAccounts refresh={() => this.handleRefreshAfterCreate()}></AddAccounts>*/}
                </div>
            </div>
        )
    };

    componentDidMount() {
    };

    /**
     * 处理账号输入框变化事件
     * @param e
     */
    handleOnChange(e) {
        this.setState({activity_name: e.target.value});
    }

    /**
     * 获取搜索条件
     */
    handleSearchComplain1() {
        let {activity_name, date, status} = this.state;
        const param = {
            activity_name,
            date,
            status
        };
        this.props.clickSearch(param);
    };

    /**
     * 处理日期选择变化事件
     * @param e
     */
    handleDateOnChange(e) {
        this.setState({date: e});
        let {activity_name, status} = this.state;
        const param = {
            activity_name,
            date: e,
            status
        };
        this.props.clickSearch(param);
    }

    /**
     * 处理状态选择变化事件
     * @param e
     */
    handleStatusOnchange(e) {
        this.setState({status: e});
        let {activity_name, date} = this.state;
        const param = {
            activity_name,
            date,
            status: e
        };
        this.props.clickSearch(param);
    }

    /**
     * 跳转到新增满减活动页面
     */
    handleRedirectToActivityAdd() {
        this.props.handleRedirectToActivityAdd();
    }
}

const SearchLists = Form.create()(SearchList);
const ActivityLists = Form.create()(ActivityList);

export default ActivityLists


